import { getAddressApi, updateAddressApi, delAddressApi } from '../../api/address'
import { getOrderInfoApi, updateOrderApi } from '../../api/order'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    defaultAddress: 0,
    list: [],
    type: 1,
    orderInfo: {},
    orderId: ''
  },

  /**
   * 获取地址列表
   */
  async getAddress() {
    const [err, list] = await getAddressApi()
    const current = list.find((item) => item.isDefault)
    if (err) return
    this.setData({
      list,
      defaultAddress: current?.id ?? 0
    })
  },

  /**
   * 删除地址
   */
  async delAddress(e) {
    const id = e.currentTarget.dataset.id
    const [err] = await delAddressApi([id])
    if (err) return
    this.getAddress()
  },

  /**
   * 切换默认地址
   */
  async onChange(event) {
    const list = JSON.parse(JSON.stringify(this.data.list))
    list.forEach((item) => {
      item.id === event.detail ? (item.isDefault = true) : (item.isDefault = false)
    })

    this.setData({
      defaultAddress: event.detail,
      list
    })

    const current = list.find((item) => item.id === event.detail)
    await updateAddressApi(current)
  },

  /**
   * 跳转新增地址
   */
  jumpEditAddress() {
    wx.navigateTo({
      url: '/pages/editAddress/editAddress'
    })
  },

  /**
   * 跳转编辑地址
   */
  jumpEditAddressToUpdate(e) {
    const addressId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/editAddress/editAddress?addressId=${addressId}`
    })
  },

  /**
   * 修改订单
   */
  async updateOrder(info, callBack) {
    const { orderListVO } = this.data.orderInfo
    const { id } = orderListVO
    const [err] = await updateOrderApi({
      id, // 订单id
      ...info
    })
    if (err) return
    callBack()
  },

  /**
   * 跳转寄回样品申请成功页面
   */
  async jumpJihuiSuccess() {
    if (this.data.list.length === 0) {
      wx.showToast({
        title: '请先添加地址',
        icon: 'none'
      })
      return
    }
    // 获取订单详情
    const [orderInfoErr, orderInfo] = await getOrderInfoApi({
      orderId: this.data.orderId
    })
    if (orderInfoErr) return

    this.setData({
      orderInfo: orderInfo
    })

    const addressIndex = this.data.list.findIndex(
      (item) => item.id === (this.data.defaultAddress ?? 0)
    )
    const currentAddress = this.data.list[addressIndex === -1 ? 0 : addressIndex]

    // const { province, city, area, name, phone, detail, id } = currentAddress
    const { id } = currentAddress
    const updateInfo =
      this.data.type === 2
        ? {
            // receiveAdress: `${province}${city}${area}`, // 收货地址
            // receiveName: name, // 收货人姓名
            // receivePhone: phone, // 收货人手机号
            // address: detail,
            specimenBackAddressId: id, // 样品寄回地址id
            specimenSendBackStatus: 2 // 样品寄回状态：1-未申请；2-已申请；3-已完成
          }
        : {
            invoiceBackAddressId: id, // 样品寄回地址id
            billStatus: 2 // 样品寄回状态：1-未申请；2-已申请；3-已完成
          }

    // 修改订单状态
    this.updateOrder(updateInfo, () => {
      wx.redirectTo({
        url: '/pages/jiuiSuccess/jiuiSuccess'
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData(
      {
        type: (options.type ?? '') === '' ? 1 : Number(options.type),
        orderId: options.orderId ?? ''
      },
      () => {
        wx.setNavigationBarTitle({
          title:
            this.data.type == 2 ? '寄回样品地址' : this.data.type == 3 ? '寄回发票地址' : '我的地址'
        })
      }
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getAddress()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
})
